﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SuiYuan.UI.Controls.Tabs
{
    /// <summary>
    /// LayUITabControl.xaml 的交互逻辑
    /// </summary>
    public partial class LayUITabControl : UserControl
    {
        public TabItemType Type
        {
            get { return (TabItemType)GetValue(TypeProperty); }
            set { SetValue(TypeProperty, value); }
        }

        public static readonly DependencyProperty TypeProperty = DependencyProperty.Register("Type", typeof(TabItemType), typeof(LayUITabControl), new PropertyMetadata(TabItemType.Default));


        /// <summary>
        /// 带关闭按钮
        /// </summary>
        public bool CloseButton
        {
            get { return (bool)GetValue(CloseButtonProperty); }
            set { SetValue(CloseButtonProperty, value); }
        }

        public static readonly DependencyProperty CloseButtonProperty = DependencyProperty.Register("CloseButton", typeof(bool), typeof(LayUITabControl), new PropertyMetadata(false));

        public void AddItem(string title, Page page)
        {
            Frame frame = new Frame();
            frame.Content = page;
            Tabcontrol1.Type = Type;
            Tabcontrol1.Visibility = Visibility.Visible;
            Tabcontrol1.Items.Add(new LayUITabItem()
            {
                Header = title,
                Type = Type,
                CloseButton = CloseButton,
                Content = frame
            });
        }

        public LayUITabControl()
        {
            InitializeComponent();
        }

        private static T FindVisualParent<T>(DependencyObject obj) where T : class
        {
            while (obj != null)
            {
                if (obj is T)
                    return obj as T;

                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }

        private void PART_Close_TabItem_Click(object sender, RoutedEventArgs e)
        {
            Button tb = sender as Button;
            LayUITabItem itemclose = FindVisualParent<LayUITabItem>(tb);
            (itemclose.Parent as TabControl).Items.Remove(itemclose);
            RoutedEventArgs args = new RoutedEventArgs(LayUITabItem.CloseItemEvent, itemclose);
            itemclose.RaiseEvent(args);
        }
    }
}
